package Presenter;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import Models.PSOLines;

public class PSOLinePresenter extends AbstractPresenter<PSOLines> {
	final String SINGLEITEM = "psoLines";
	final String MULTIITEM = "pSOLiness";
	
	public PSOLines getEmptyEntity(){
		PSOLines entity = new PSOLines();
		return entity;
	}
	
	public ArrayList<PSOLines> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public PSOLines tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public PSOLines createItemFromJSONObject(JSONObject jsonObject){
		PSOLines item = new PSOLines();
		try{
			item.setPsoID(jsonObject.getInt("PSOID"));
			item.setKeg(jsonObject.getInt("PSOKeg"));
			item.setQty(jsonObject.getInt("PSOQty"));
			item.setQtyLeft(jsonObject.getInt("PSOQtyLeft"));
			item.setPriceOverRide(jsonObject.getDouble("PSOPriceOverRide"));
			item.setSold(jsonObject.getBoolean("PSOSold"));

			DiscountCodePresenter dcPresenter = new DiscountCodePresenter();
			JSONObject jsonDisc = jsonObject.getJSONObject("PSODiscCode");
			item.setDiscount(dcPresenter.createItemFromJSONObject(jsonDisc));
			
			FGIViewPresenter fgiPresenter = new FGIViewPresenter();
			JSONObject jsonFGI = jsonObject.getJSONObject("PSOFGI");
			item.setFgi(fgiPresenter.createItemFromJSONObject(jsonFGI));
			
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(PSOLines item){
		try{
			JSONObject json = new JSONObject();
			json.put("PSOID", item.getPsoID());
			json.put("PSOKeg", item.getKeg());
			json.put("PSOQty", item.getQty());
			json.put("PSOQtyLeft", item.getQtyLeft());
			json.put("PSOPriceOverRide", item.getPriceOverRide());
			json.put("PSOSold", item.isSold());

			if(item.getDiscount()!=null){
				DiscountCodePresenter presenter = new DiscountCodePresenter();
				json.put("PSODiscCode", presenter.createJSON(item.getDiscount()));
			} else {
				json.put("PSODiscCode", JSONObject.NULL);
			}
			
			FGIViewPresenter fgiPresenter = new FGIViewPresenter();
			json.put("PSOFGI", fgiPresenter.createJSON(item.getFgi()));
			
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}

}
